package vn.mahjonggame.zone.request;

import java.util.List;
import vn.mahjonggame.util.Common;
import vn.mahjonggame.metadata.GameActionType;
import vn.mahjonggame.metadata.MatchState;
import vn.mahjonggame.metadata.PlayerMode;
import vn.mahjonggame.metadata.MObject;
import vn.mahjonggame.metadata.RoomVarName;
import vn.mahjonggame.metadata.UserVarName;
import vn.mahjonggame.platform.GameplayConfig;
import vn.mahjonggame.platform.PlatformClient;
import vn.mahjonggame.platform.PlatformConfig;

import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.exceptions.SFSJoinRoomException;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;

public class JoinMahjongRoomRequestHandler extends BaseClientRequestHandler {	

	@Override
	public void handleClientRequest(User user, ISFSObject params) {
		// TODO Auto-generated method stub
		int roomId = params.getInt("roomID").intValue();
		String roomPassword = params.getUtfString("roomPassword");
		Room room = getParentExtension().getParentZone().getRoomById(roomId);
		
		SFSObject response = null;
		
		if (room == null) 
		{
			String msg = "Room is not found";
			response = new SFSObject();
			response.putUtfString(MObject.message.toString(), msg);
			send(GameActionType.join_fail.toString(), response, user);
			
			trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());
			return;
		}
		
		List<User> users = room.getUserList();
		
		if(users.size() > 3){
			String msg = "room is full";
			response = new SFSObject();
			response.putUtfString(MObject.message.toString(), msg);
			send(GameActionType.join_fail.toString(), response, user);
			
			trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());
			return;
		}
		
		/*
		 * The game was started
		 */
		int matchState = room.getVariable(RoomVarName.roomState.toString()).getIntValue();
		
		if (matchState == MatchState.PLAYING.ordinal()
				|| matchState == MatchState.SHOW_RESULT.ordinal())
		{			
			String msg = "game is started";
			response = new SFSObject();
			response.putUtfString(MObject.message.toString(), msg);			
			
			send(GameActionType.join_fail.toString(), response, user);
			
			trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());
			return;
		}
		
		int roomBet = room.getVariable(RoomVarName.roomBet.toString()).getIntValue();
		
		/*
		 * Get the default balance
		 */
		int play_mode = room.getVariable(RoomVarName.playMode.toString()).getIntValue();		
		double userBalance = Double.valueOf(room.getVariable(RoomVarName.tutorial_balance.toString()).getStringValue());
		
		/*
		 * Get the balance from Widocom
		 */
		if (play_mode == PlayerMode.REAL_MODE.ordinal()){
			userBalance = user.getVariable(UserVarName.balance.toString()).getDoubleValue();			
			
			String access_token = user.getVariable(UserVarName.access_token.toString()).getStringValue();
			
			trace(ExtensionLogLevel.INFO, GameActionType.join.toString() + ": Start user_get_balance");
			
			response = PlatformClient.user_get_balance(access_token);
			
			if (Common.isApiSuccess(response)) {
				String balanceText = response.getSFSObject("response").get("balance").getObject().toString();
				userBalance = Double.parseDouble(balanceText);
			}
			else {
				String msg = "Failed in user_get_balance API";
				response = new SFSObject();
				response.putUtfString(MObject.message.toString(), msg);			
				
				send(GameActionType.join_fail.toString(), response, user);
				
				trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());
				return;				
			}
			
			trace(ExtensionLogLevel.INFO, GameActionType.join.toString() + ": End user_get_balance");
		}
		
		if (userBalance < roomBet)
		{
			SFSObject data = new SFSObject();
			data.putDouble(UserVarName.balance.toString(), userBalance);
			data.putInt(RoomVarName.roomBet.toString(), roomBet);
			
			String msg = "your balance is not enough";
			response = new SFSObject();
			response.putUtfString(MObject.message.toString(), msg);			
			
			send(GameActionType.join_fail.toString(), response, user);
			
			trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());			
			return;
		}			

		try {
			if (roomPassword.length() == 0) roomPassword = null;
			
			getApi().joinRoom(user, room, roomPassword, false, null, true, true);										
			
		} catch (SFSJoinRoomException e) {
			trace(ExtensionLogLevel.ERROR, String.valueOf(e.getStackTrace()));			
			
			String msg = "Failed in SFS API";
			response = new SFSObject();
			response.putUtfString(MObject.message.toString(), msg);			
			
			send(GameActionType.join_fail.toString(), response, user);
			
			trace(ExtensionLogLevel.ERROR, GameActionType.join.toString() + ": " + msg + "-" + user.getName());			
			return;			
		}
		
		trace(ExtensionLogLevel.INFO, GameActionType.join.toString() + ": User " + user.getName() + "("+user.getId()+")");
	}
}
